<?php
namespace app\app\controller\v1;
use app\app\Appbase;
use base\pay\WxApi;
use base\pay\AliPayApi;

class Order extends Appbase 
{
	
	/**
	* 确认订单
	* /app/v1/order/confirm
	* 需要登录 
	* @is_need_login true
	* @method post 
	*/
	public function confirm(){
		$request =  request();
		$param = $request ->post();
		$user = $request->userInfo;
		$uid = $request->userId;
		
		//TODO 获取post参数
    	list($cartIds,$couponId,$addressId,$activityId,$deliveryType) = [
    		$param['cart_ids'] ?: '',
    		$param['coupon_id'] ?: 0,
    		$param['address_id'] ?: 0,
    		$param['activity_id'] ?: 0,
    		$param['delivery_type'] ?? 1,
    	];
    	
    	if( $deliveryType === '' || $deliveryType < 0 || $deliveryType>1) {
    		return $this->ReError('配送方式错误！');
    	}
		
		// TODO 参数效验
		if(!$cartIds) return $this->ReError('购物车id不存在！');
		
		try {
			
			// TODO 确认订单
			$model = model('order');
			$model = $model->setCoupon($couponId);
			$model = $model->setAddress($addressId);
			$model = $model->setActivity($activityId);
			$model = $model->setDeliveryType($deliveryType);
			$res = $model->confirm($cartIds);
			
			return $this->ReSucess($res);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());
		}
	}
	
	/**
	* 确认后创建订单
	* /app/v1/order/create
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function create($orderKey,$pay_type,$mark=''){
		if( !trim($orderKey) ) return $this->ReError('orderKe不能为空！');
		if( !trim($pay_type) ) return $this->ReError('付款方式不能为空！');
		
		$dbOrder = model('Order');
		
		\Db::startTrans();
		try {
			
			//生成订单
			$payType = strstr($pay_type,"wx") ? 'wx'  : $pay_type; 
			$order = $dbOrder->setMark($mark)->setPayType($payType)->createOrder($orderKey);
			
			//生成付款信息
            $orderId = $order['id'];
			$orderNo = $order['order_no'];
			$payPrice = $order['pay_price'];
			$paySign = [];
			
			//支付金额为0 - 直接支付
            if (bcsub((float)$payPrice, 0, 2) <= 0) {
                $payPriceStatus = $dbOrder->paySuccess($orderNo);
				$order->is_pay = 1;
            }else{
            	$wxapi = new WxApi($pay_type);
	            switch ($pay_type) {
	                case "wx_h5":
	                case "applets": 
	                case "wx": //调起微信app
	                    $paySign = $wxapi->createOrder($orderNo,$payPrice);
	                    break;
					case "alipay": //支付宝支付
						$paySign = (new AliPayApi)->tradeAppPay($orderNo,$payPrice);
	                    break;	
					case 'brokerage': 	//佣金支付		
	                    if ($dbOrder->brokeragePay($orderId)){
	                    	$order->is_pay = 1;
	                    }
	                    break;
	                case 'balance': //余额支付		
						if ($dbOrder->balancePay($orderId)){
	                    	$order->is_pay = 1;
	                    }
	                    break;
	            }
            } 
            
            event('OrderCreated', $order); //订单创建成功事件
            
			\Db::commit();
			return $this->ReSucess(compact('order', 'paySign', 'is_pay'));
		} catch (\Exception $e) {
			\Db::rollback();
			return $this->ReError( $e->getMessage() );
		}
	}

	 /**
     * 订单支付
     * @param Request $request
     * @return mixed
     */
    public function pay($order_no='',$pay_type='')
    {
		if(!trim($order_no)) return $this->ReError('订单编号不能为空！');
		if(!trim($pay_type)) return $this->ReError('付款方式不能为空！');
		$uid = request()->userId;
		
		try {
			$dbOrder = model('Order');
			$order = $dbOrder->getOrderDetail($order_no);
	        if ($order['is_pay'] == 1 || $order['status'] != 0){
	        	return $this->ReError('该订单已支付!');
	        }
			$orderId = $order['id'];
			$paySign = [];
			$is_pay = 0;
			
			//支付金额为0 - 直接支付
	        if ( bcsub((float)$order['pay_price'], 0, 2) <= 0) {
	            $payPriceStatus = $dbOrder->paySuccess($order['order_no']);
	            $order = $dbOrder->find($orderId);
				$is_pay = 1;
	        }else{
	        	$wxapi = new WxApi;
	            switch ($pay_type) {
	                case "wx_h5":
	                case "wx_applets": //微信内支付
	                    $paySign = $wxapi->createOrder($order['order_no'],$order['pay_price'],$pay_type);
	                    break;
	                case "wx": //调起微信app
		                $paySign = $wxapi->createOrder($order['order_no'],$order['pay_price'],$pay_type,'MWEB');
	                    break;
					case "alipay": //支付宝支付
	                   	$paySign = (new AliPayApi)->tradeAppPay($order['order_no'],$order['pay_price']);
	                    break;	
					case 'brokerage': 	//佣金支付		
	                    if ($dbOrder->brokeragePay($orderId,$uid)){
	                    	$order = $dbOrder->find($orderId);
	                    	$is_pay = 1;
	                    }
	                    break;
	                case 'balance': //余额支付		
						if ($dbOrder->balancePay($orderId,$uid)){
							$order = $dbOrder->find($orderId);
	                    	$is_pay = 1;
	                    }else{
	                    	return $this->ReError(  $dbOrder->errorInfo );
	                    }
	                    break;
	            }
	        }
			
			return $this->ReSucess(compact( 'order', 'paySign', 'is_pay'));
			
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
    }
	
	/**
	*获取订单列表
	* /app/v1/order/getList
	* 需要登录 
	* @is_need_login true
	* @method get
	*/
	public function getList($name=''){
		$where[] = ['uid', '=', request()->userId ];
		//$where[] = ['shop_id', '=', request()->shopId ];
		if(!empty($name)){
			$where[] = ['order_no', 'like', "%$name%"];
		}
		$param = request()->get();
		if($param['status'] == -1){
			$where[] = ['refund_status', '<>', '0'];
		}else if(trim($param['status']) != ''){
			$where[] = ['status', '=', $param['status']];
			$where[] = ['refund_status', 'in', '0,1'];
		}
		if(!empty($param['is_pay']) || $param['is_pay'] === 0  || $param['is_pay'] === '0'){
			$where[] = ['is_pay', 'in', $param['is_pay']];
		}
		try {
			$result = model('order')->getList($where,$pageIndex,$pageSize);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
	}
	
	
	/**
	*获取订单明细
	* /app/v1/order/details
	* 需要登录 
	* @is_need_login true
	* @method all
	*/
	public function details($id){
		if(!$id){
			return $this->ReError('订单id不能为空！');
		}
		try {
			$result = model('order')->details($id);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
	}
	
	/**
	* 查看订单是否支付完成
	* /app/v1/order/isPay
	* 需要登录 
	* @is_need_login true
	* @method get
	*/
	public function isPay($order_no){
		if(!$order_no){
			return $this->ReError('订单编号不能为空！');
		}
		try {
			$is_pay = model('order')->where("order_no",$order_no)->value('is_pay');
			return $this->ReSucess($is_pay);	
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
	}
	
	/**
     * 订单 再次下单
     * @param Request $request
     * @return mixed
     */
    public function again($id)
    {
    	if(!$id){
			return $this->ReError('订单id不能为空！');
		}
		$user = request()->userInfo;
		$uid = request()->userId;
		$param = request()->post();
		try {
	        $order = model('Order')->getUserOrderDetail($uid,$id);
	        if (!$order) {
	        	return $this->ReError('订单不存在！');
	  		}
	        $order = model('Order')->tidyOrder($order, true);
	        $res = [];
	        foreach ($order['cartInfo'] as $v) {
	            if ($v['seckill_id']) {
	            	return $this->ReError('秒杀产品不能再来一单，请在秒杀产品内自行下单!！');
	            } else {
	            	$res[] = model('ShopCart')->setCartInc($uid,$v['goods_id'],$v['cart_num'],0,$v['specs_id'], 1);
	            }
	        }
	        $cateId = [];
	        foreach ($res as $v) {
	        	if (!$order) {
	        		return $this->ReError('再来一单失败，请重新下单！');
	  			}
	            $cateId[] = $v['id'];
	        }
			return $this->ReSucess(['cateId' => implode(',', $cateId)]);
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
    }
	
    /**
	*订单删除
	* /app/v1/order/del
	* 需要登录 
	* @is_need_login true
	* @method all
	*/ 
    public function del($id)
    {
    	if(!$id) return $this->ReError('订单id不能为空！');
		try {
	      	$result = model('order')->removeOrder($id);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
    }
	
	
   /**
	*订单收货
	* /app/v1/order/take
	* 需要登录 
	* @is_need_login true
	* @method all
	*/  
    public function take($id)
    {
    	if(!$id) return $this->ReError('订单id不能为空！');
		try {
	      	$result = model('order')->takeOrder($id);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
    }
	
	/**
	*订单申请退款
	* /app/v1/order/applyRefund
	* 需要登录 
	* @is_need_login true
	* @method post
	*/  
    public function applyRefund()
    {
		try {
		   $param = request()->post();
	        //获取参数
	    	list($orderId,$wap,$explain,$img,$type,$price) = [
	    		$param['order_id'] ?: 0,
	    		$param['refund_wap'] ?: '',
	    		$param['refund_explain'] ?: '',
	    		$param['refund_img'] ?: '',
	    		$param['refund_type'] ?: '',
	    		$param['refund_price'] ?: ''
	    	];
			if(!$orderId) return $this->ReError('订单id不能为空！');
			if(empty($wap)) return $this->ReError('退款原因必填！');
			if(empty($type)) return $this->ReError('退款类型必填！');
			if(empty($price)) return $this->ReError('退款价格必填！');
	        $uid = request()->userId;
			$result = model('order')->orderApplyRefund($orderId,$wap,$explain,$img,$type,$price);
		return $this->ReSucess();	
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
    }
	
	/**
	*订单主动取消   未支付的订单回退积分,回退优惠券,回退库存
	* /app/v1/order/cancel
	* 需要登录 
	* @is_need_login true
	* @method all
	*/  
    public function cancel($id)
    {
    	if(!$id) return $this->ReError('订单id不能为空！');
    	try {
	        $result = model('order')->cancelOrder($id);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError( $e->getMessage() );
		}
    }
	
	
	/**
	*过期未支付 订单自动取消   未支付的订单回退积分,回退优惠券,回退库存
	* /app/v1/order/unpaidCancel
	* 需要登录 
	* @is_need_login true
	* @method all
	*/  
    public function unpaidCancel()
    {
        $result = model('common/order')->orderUnpaidCancel();
		if(!$result){
		  	return false;
		}else{
			return true;	
		}
    }
	
	/**
	*过期收货 订单自动收货
	* /app/v1/order/startTakeOrder
	* 需要登录 
	* @is_need_login true
	* @method all
	*/  
    public function startTakeOrder()
    {
        $result = model('common/order')->startTakeOrder();
		if(!$result){
		  	return false;
		}else{
			return true;	
		}
    }
	
}



